import { db, _ } from "./cloudInit.js";

import pick from "@/node_modules/lodash-es/pick.js";
import { Public, UnPublic, Feedback, Favorite } from "./user/Xin.js";
import { compress } from "@/utils/pictureCompress.js";
export default {
    state: () => ({
        userInfo: {
            UserInfo: {
                likeArray: [],
            },
            avatarUrl: "",
            nickName: "未登录",
            isManager: false,
        },
        myXin: { UnPublic, Public },
        Feedback,
        needLogin: false,
        Favorite,
    }),
    mutations: {
        changeMyXin(state, { isPublic, data = [] }) {
            console.log("我的心语签", data);
            state.myXin[isPublic ? "Public" : "UnPublic"] = data;
        },
        updateUser(state, userInfo) {
            console.info("更新用户信息", userInfo);
            if (userInfo.state !== "none") {
                state.userInfo = userInfo;
                state.needLogin = false;
                // 向 Favorite 更新 openId
                state.Favorite.openId = userInfo.openId;
                console.log("用户登录信息", userInfo);
            } else {
                state.needLogin = true;
                console.log("未登录");
            }
        },
        callbackLike(state, { isLiked, _id }) {
            if (isLiked) {
                state.userInfo.UserInfo.likeArray.push(_id);
            } else {
                state.userInfo.UserInfo.likeArray =
                    state.userInfo.UserInfo.likeArray.filter((i) => i !== _id);
            }
        },
    },
    actions: {
        async changeLike({ state, commit }, { isLiked, _id }) {
            console.log(isLiked);
            return db
                .collection("UserInfo")
                .doc(state.userInfo.openId)
                .update({
                    data: {
                        likeArray: isLiked ? _.addToSet(_id) : _.pull(_id),
                    },
                })
                .then(() => commit("callbackLike", { isLiked, _id }));
        },
        async changeUserData({ state, commit }, data) {
            return wx.cloud
                .callFunction({
                    name: "ChangeUser",
                    data: {
                        USER: data,
                    },
                })
                .catch((err) => {
                    console.error(err);
                });
        },
        async login({ commit }, userInfo) {
            console.warn("用户登录", userInfo);

            return wx.cloud
                .callFunction({
                    name: "UserLogin",
                    data: {
                        USERINFO: userInfo,
                    },
                })
                .then(({ result }) => commit("updateUser", result))
                .catch((err) => {
                    commit("updateUser", { state: "none" });
                    console.error(err);
                });
        },
        async uploadFeedback({ state }, feed) {
            const timestamp = `${
                state.userInfo.openId
            }-${new Date().getTime()}`;

            // 使用 pick 方式是为了保证上传安全
            const needKey = ["title", "desc", "position"];
            return db
                .collection("Feedback")
                .add({
                    data: {
                        ...pick(feed, needKey),
                        picture: feed.pictures.map((_, index) => {
                            return `cloud://xinyuqian-5gvjlw4d0eabb09e.7869-xinyuqian-5gvjlw4d0eabb09e-1307420821/user/${timestamp}-${index}.png`;
                        }),
                        createTime: new Date().getTime(),
                        isDone: false,
                    },
                })
                .then((res) => {
                    return Promise.all(
                        feed.pictures.map(async ({ url }, index) => {
                            const compressed = await compress(url);
                            return wx.cloud
                                .uploadFile({
                                    cloudPath: `user/${timestamp}-${index}.png`, // 上传至云端的路径
                                    filePath: compressed, // 小程序临时文件路径
                                })
                                .then((res) => res.fileID);
                        })
                    );
                });
        },
    },
    getters: {
        total(state) {
            return {
                Public: state.myXin.Public.total,
                UnPublic: state.myXin.UnPublic.total,
                Feedback: state.Feedback.total,
            };
        },
    },
};
